package org.wanho.rent.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import org.wanho.rent.entity.SysUser;
import org.wanho.rent.entity.SysUser;
import org.wanho.rent.exception.LoginException;
import org.wanho.rent.factory.ObjectFactory;
import org.wanho.rent.service.SysuserService;
import org.wanho.rent.util.AjaxResult;
import org.wanho.rent.util.CommonUtil;
import org.wanho.rent.util.ResponseUtil;

/**
 * 用户控制器
 * @author student
 *
 */

@WebServlet(urlPatterns = "*.user")
public class SysUserController extends HttpServlet {
	
	private SysuserService sysuserServiceProxy = (SysuserService) ObjectFactory.getObject("sysuserServiceProxy");
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(request.getServletPath() + "###");
		String servletPath = request.getServletPath();
		if (servletPath.equals("/selectUser.user")) {
			System.out.println("-========login=============");
			selectUser(request, response);
		} else if (servletPath.equals("/modifyPwd.user")) {
			modifyPwd(request, response);

		}

	}

	/**
	 * 修改密码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void modifyPwd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
		String reNewPwd = request.getParameter("reNewPwd");

		System.out.println(oldPwd + "#" + newPwd + "$" + reNewPwd);

		
		// 返回数据到浏览器
		ResponseUtil.doResponse("修改成功！", new SysUser(1, "zhangsan", "13376053661", "123"), true, response);

	}

	/**
	 * 用户登录
	 * @param request
	 * @param response
	 */
	private void selectUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		System.out.println(userName + "#" + pwd);

		if (userName == null || userName.equals("")) {
			// 返回数据到浏览器
			ResponseUtil.doResponse("用户名不为空！", null, false, response);
			return;
		}

		// 调用Service层实现业务功能
		try {
			SysUser user = sysuserServiceProxy.login(userName, pwd);
			// 返回数据到浏览器
			ResponseUtil.doResponse("登陆成功！", user, true, response);
		} catch (Exception e) {
			ResponseUtil.doResponse(e.getMessage(), null, false, response);
		}

	}

}
